package me.shan.data.structure;

import java.util.List;

/**
 * 描述：使用链表实现的栈
 *
 * @author liuchuang
 * @date 2021/7/8 14:00
 */
public class QueueStack {

    private ArrayQueue queueA;

    private ArrayQueue queueB;

    public QueueStack() {
        this.queueA = new ArrayQueue();
        this.queueB = new ArrayQueue();
    }

    public void push(int value) throws Exception {
        if (this.queueA.getSize() == 0 && this.queueB.getSize() == 0) {
            this.queueA.add(value);
        } else if (this.queueA.getSize() > 0) {
            this.queueA.add(value);
        } else if (this.queueB.getSize() > 0) {
            this.queueB.add(value);
        }
    }

    public int pop() throws Exception {
        if (this.queueA.getSize() == 0 && this.queueB.getSize() == 0) {
            throw new Exception("空栈，不允许pop操作");
        } else if (this.queueA.getSize() > 0) {
            while (this.queueA.getSize() > 1) {
                this.queueB.add(this.queueA.remove());
            }
            return this.queueA.remove();
        } else {
            while (this.queueB.getSize() > 1) {
                this.queueA.add(this.queueB.remove());
            }
            return this.queueB.remove();
        }
    }

    @Override
    public String toString() {
        ArrayQueue queue = this.queueA.getSize() == 0 ? this.queueB : this.queueA;
        if (queue.getSize() == 0) {
            return "QueueStack{ null }";
        } else {
            List<Integer> list = queue.getElementDataList();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("QueueStack{ ");
            for (Integer value : list) {
                stringBuilder.append(value).append(", ");
            }
            stringBuilder.append("}");
            return stringBuilder.toString();
        }
    }

    public static void main(String[] args) throws Exception {
        QueueStack stack = new QueueStack();
        stack.push(1);
        System.out.println(stack.pop());
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop());
        stack.push(4);
        System.out.println(stack.pop());
        stack.push(5);
        System.out.println(stack.pop());
        stack.push(6);
    }
}
